package org.example.protocol.http;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @Author: luyg
 * @Date: 2024/08/21/2:25
 * @Description:
 */
public class HttpServer {

    public void start(String host,Integer port){
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service tomcat1 = server.findService("tomcat");

        Connector connector = new Connector();
        connector.setPort(port);

        StandardEngine standardEngine = new StandardEngine();
        standardEngine.setDefaultHost(host);

        StandardHost standardHost = new StandardHost();
        standardHost.setName(host);

        String contextPath="";
        StandardContext standardContext = new StandardContext();
        standardContext.setPath(contextPath);
        standardContext.addLifecycleListener(new Tomcat.FixContextListener());

        standardHost.addChild(standardContext);
        standardEngine.addChild(standardHost);

        tomcat1.setContainer(standardEngine);
        tomcat1.addConnector(connector);

        tomcat.addServlet(contextPath,"dispathcer",new DispatcherServlet());
        standardContext.addServletMappingDecoded("/*","dispathcer");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }
}
